package forest.app;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.webkit.CookieSyncManager;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;



public class MainActivity extends Activity {

    private WebView m_webview;
    private ValueCallback<Uri> m_upload_msg;

    private final int REQUEST_IMAGE_CAPTURE = 1000;

    private File m_cam_img_file = null;
    private String m_barcode_data = null;

    private CookieManager m_cookie_mgr = null;

    private final String HOME_URL_PROD = "http://10.0.1.188/posx/mobile";
    private final String HOME_URL_DEV = "http://10.0.1.38/posx/mobile";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getActionBar().hide();

        CookieSyncManager.createInstance(this);
        m_cookie_mgr = CookieManager.getInstance();
        m_cookie_mgr.removeAllCookie();

        m_webview = (WebView)findViewById(R.id.webView);
        m_webview.setWebViewClient(new WebViewClient());
        WebSettings settings = m_webview.getSettings();
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setJavaScriptEnabled(true);
        m_webview.addJavascriptInterface(new WebAppInterface(this), "Android");

        m_webview.loadUrl(HOME_URL_PROD);

    }

    @Override
    public void onBackPressed() {
        m_webview.loadUrl(HOME_URL_PROD);

        //super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        m_cookie_mgr.removeAllCookie();
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode != RESULT_OK) return;

        if (requestCode == REQUEST_IMAGE_CAPTURE) {
            if(m_cam_img_file == null) return;

            m_webview.loadUrl("javascript:window.OnPictureReady && window.OnPictureReady()");

        } else if(requestCode == IntentIntegrator.REQUEST_CODE) {
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if(result == null) return;

            m_barcode_data = result.getContents();
            m_webview.loadUrl("javascript:window.OnBarcodeReady && window.OnBarcodeReady()");
        }


    }


    public class WebAppInterface {
        Context m_ctx;

        WebAppInterface(Context c) {
            m_ctx = c;
        }


        @JavascriptInterface
        public void setDevMode() {
            m_webview.loadUrl(HOME_URL_DEV);
        }

        @JavascriptInterface
        public void scanBarcode() {
            m_barcode_data = null;

            IntentIntegrator scan = new IntentIntegrator((Activity)m_ctx);
            scan.initiateScan();
        }

        @JavascriptInterface
        public String getBarcode() {
            String ret = m_barcode_data;
            m_barcode_data = null;
            return ret;
        }

        @JavascriptInterface
        public void takePicture() {
            m_cam_img_file = null;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

                try {
                    m_cam_img_file = File.createTempFile("CAM_IMG_", ".jpg", dir);
                    m_cam_img_file.deleteOnExit();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(m_cam_img_file));
                    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);

                } catch (IOException e) {

                }

            }
        }

        @JavascriptInterface
        public String getPicture() {
            if(m_cam_img_file == null) return null;

            String ret = null;
            try {
                Bitmap img = BitmapFactory.decodeStream( new FileInputStream(m_cam_img_file) );

                int w = img.getWidth();
                int h = img.getHeight();
                float nw = w;
                float nh = h;
                if(w >= h) {
                    if(w > 1200) {
                        nh = nh / nw * 1200;
                        nw = 1200;
                    }
                } else {
                    if(h > 1200) {
                        nw = nw / nh * 1200;
                        nh = 1200;
                    }
                }

                img = Bitmap.createScaledBitmap(img, (int)nw, (int)nh, true);

                ByteArrayOutputStream os = new ByteArrayOutputStream();
                img.compress(Bitmap.CompressFormat.JPEG, 85, os);

                ret = Base64.encodeToString(os.toByteArray(), Base64.DEFAULT);

            } catch(FileNotFoundException ex) {

            } catch(IOException ex) {

            } finally {
                m_cam_img_file.delete();
                m_cam_img_file = null;

            }

            return ret;
        }

    }


}
